package com.fingard.dsp.bank.directbank.jhbank01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.DateFormat2;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.jhbank01.utils.PublickeyEncript;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/7/20.
 */
public class JHBANK01Transaction extends JHBANK01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();
        String respCode ="";
        String respInfo ="";
        Calendar tmpCalFrom = Calendar.getInstance();
        tmpCalFrom.setTime(Format.Date8Format.parse(p_req7516.dateFrom));
        Calendar tmpCalTo = Calendar.getInstance();
        tmpCalTo.setTime(Format.Date8Format.parse(p_req7516.dateTo));
        int dateFrom = Integer.valueOf(p_req7516.dateFrom);
        int dateTo =Integer.valueOf(p_req7516.dateTo);
        try{
            while (dateFrom<=dateTo && StringHelper.isNullOrEmpty(respCode)){
                Calendar tmpCalStep = Calendar.getInstance();
                tmpCalStep.setTime(tmpCalFrom.getTime());
                if(DateHelper.compareMonth(tmpCalFrom,tmpCalTo)==-1) {
                    tmpCalStep.set(Calendar.DAY_OF_MONTH, tmpCalFrom.getActualMaximum(Calendar.DAY_OF_MONTH));
                }else{
                    tmpCalStep.setTime(tmpCalTo.getTime());
                }
                    String lastTransDt ="";
                    String lastTransSeq ="";
                    while (true){
                        XmlTextWriter xmlTextWriter = new XmlTextWriter();
                        JHBANK01Header header = new JHBANK01Header();
                        header.userid=bankFront.operator;
                        String nodeNo = getBankConfig().getValueAsString("nodeNo");
                        header.brchno =nodeNo;
                        header.servtp ="";
                        header.prcscd = "QCA02";
                        writeCommenHeader(xmlTextWriter,header);
//                        tellNo	tellNo	操作员号	X	4
//                        nodeNo	nodeNo	财政局标示	X	5	88883
//                        tranCode	tranCode	交易代码	X	15	交易码：QCA02
//                        accountNo	accountNo	账号	X	32
//                        subAccountNo	subAccountNo	子账户	N	6
//                        currencyType	currencyType	币种	S	2	01：人民币
//                        beginDate	beginDate	交易起始时间		8
//                        endDate	endDate	交易结束日期		8
//                        PageShowNum	PageShowNum	每页记录数		8	最大15，不易太多，太多返回较慢
//                        lastTransDt	lastTransDt	每页最大日期		20
//                        lastTransSeq	lastTransSeq	每页最大流水		20
                        xmlTextWriter.writeStartElement("Body");
                        xmlTextWriter.writeElementString("tellNo",bankFront.operator,true);
                        xmlTextWriter.writeElementString("nodeNo",nodeNo,true);
                        xmlTextWriter.writeElementString("tranCode","QCA02",true);
                        xmlTextWriter.writeElementString("accountNo",p_req7516.actNum,true);
                        xmlTextWriter.writeElementString("subAccountNo","00001",true);
                        xmlTextWriter.writeElementString("currencyType",convertCurToBank(p_req7516.actCur),true);
                        xmlTextWriter.writeElementString("beginDate",Format.Date8Format.format(tmpCalFrom.getTime()),true);
                        xmlTextWriter.writeElementString("endDate",Format.Date8Format.format(tmpCalStep.getTime()),true);
                        xmlTextWriter.writeElementString("PageShowNum","5",true);
                        xmlTextWriter.writeElementString("lastTransDt",lastTransDt,true);
                        xmlTextWriter.writeElementString("lastTransSeq",lastTransSeq,true);
                        xmlTextWriter.writeEndDocument();
                        String[] bankResult = sendToBank(xmlTextWriter.toXmlString());
                        if(bankResult[0].length()==0){
                            StringBuilder tmpSbMsg = new StringBuilder();
                            XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1],tmpSbMsg);
                            if(tmpBkReader!=null){
                                int offset =bankResult[1].indexOf("<hostReturnCode>");
                                int endset =bankResult[1].indexOf("</hostReturnCode>")+"</hostReturnCode>".length();
                                String source  = bankResult[1].substring(offset,endset);
                                offset =bankResult[1].indexOf("<hostErrorMessage>");
                                endset =bankResult[1].indexOf("</hostErrorMessage>")+"</hostErrorMessage>".length();
                                source = source+bankResult[1].substring(offset,endset);
                                String hostReturnEncrypt = tmpBkReader.getFirstText("/root/hostReturnEncrypt");
                                boolean b= PublickeyEncript.checkSign(source, hostReturnEncrypt,getBankConfig().getValueAsString("certificatePath"));
                                if(!b){
                                    respCode = "-1";
                                    respInfo = "验签不通过";
                                    break;
                                }else{
                                    String hostReturnCode = tmpBkReader.getFirstText("/root/hostReturnCode");
                                    if ("0000".equals(hostReturnCode)) {
                                        int pageNum = 0;
                                        while (tmpBkReader.read("/root/list/row")) {
                                            pageNum++;
                                            RetAtsTransDetail detail = new RetAtsTransDetail();
                                            detail.actNum = p_req7516.actNum;
                                            detail.accBal = tmpBkReader.readedXElement.getSingleTextNotNull("recAccountName");
                                            detail.cur = convertCurToATS(tmpBkReader.readedXElement.getSingleTextNotNull("currencyType"));
                                            detail.recAccName = tmpBkReader.readedXElement.getSingleTextNotNull("recAccount");
                                            detail.recAccNum = tmpBkReader.readedXElement.getSingleTextNotNull("payAccOpenBankNm");
                                            String dateStr =tmpBkReader.readedXElement.getSingleTextNotNull("transferDate");//yyyymmdd
                                            lastTransDt = dateStr;
                                            String timeStr = tmpBkReader.readedXElement.getSingleTextNotNull("transferTime");//hh:mm:ss:ssss
                                            Date date =new DateFormat2("yyyyMMdd hh:mm:ss").parse(dateStr+" "+timeStr.substring(0,8));
                                            detail.tranDate = Format.Date10Format.format(date);
                                            detail.valueDate = detail.tranDate;
                                            detail.tranTime = Format.DateTimeFormat.format(date);
                                            //备注
                                            detail.usage = tmpBkReader.readedXElement.getSingleTextNotNull("Info");
                                            detail.abstr = pickupAbstr(detail.usage);
                                            detail.originator = tmpBkReader.readedXElement.getSingleTextNotNull("coreFlowNo");
                                            lastTransSeq = detail.originator;

                                            String cdFlag = tmpBkReader.readedXElement.getSingleTextNotNull("loanFlag");
                                            String tranAmt = tmpBkReader.readedXElement.getSingleTextNotNull("payAccount");//借方发生额
                                            if ("D".equals(cdFlag)) {
                                                int flag = 0;
                                                if (StringHelper.isNullOrEmpty(tranAmt)||"0.00".equals(tranAmt)) {
                                                    tranAmt = tmpBkReader.readedXElement.getSingleTextNotNull("payAccountNm");//贷方发生额
                                                    flag++;
                                                }
                                                if (tranAmt.indexOf("-") != -1) {
                                                    flag++;
                                                    tranAmt = tranAmt.substring(1);
                                                }
                                                detail.cdFlag = flag % 2 == 0 ? "1" : "2";
                                                detail.tranAmt = tranAmt;
                                            } else if ("C".equals(cdFlag)) {
                                                int flag = 1;
                                                if (StringHelper.isNullOrEmpty(tranAmt)||"0.00".equals(tranAmt)) {
                                                    tranAmt = tmpBkReader.readedXElement.getSingleTextNotNull("payAccountNm");//贷方发生额
                                                    flag++;
                                                }
                                                if (tranAmt.indexOf("-") != -1) {
                                                    flag++;
                                                    tranAmt = tranAmt.substring(1);
                                                }
                                                detail.cdFlag = flag % 2 == 0 ? "2" : "1";
                                                detail.tranAmt = tranAmt;
                                            } else {
                                                respCode = "-1";
                                                respInfo = "借贷标识: " + cdFlag + "无法识别";
                                                break;
                                            }
                                            retAts.writeRetDetail(detail);
                                        }
                                        //返回的报文中没有明细记录，表示当前月份查询完毕
                                        if (pageNum == 0||"-1".equals(respCode)) {
                                            break;
                                        }
                                    } else {
                                        respCode = "-1";
                                        respInfo = tmpBkReader.getFirstText("/root/hostErrorMessage");
                                        break;
                                    }

                                }
                            }else {
                                respCode ="-1";
                                respInfo =tmpSbMsg.toString();
                                break;
                            }
                        }else {
                            respCode = "-1";
                            respInfo = bankResult[1];
                            break;
                        }
                    }
                    tmpCalFrom = tmpCalStep;
                    tmpCalFrom.add(Calendar.DAY_OF_MONTH,1);
                    dateFrom = Integer.valueOf(Format.Date8Format.format(tmpCalFrom.getTime()));
                }
        }catch (Exception ex){
            respCode="-1";
            respInfo=ex.getMessage();
            ex.printStackTrace();
        }
        if ("-1".equals(respCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(respCode);
            retAts.writeRespInfo(respInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 =new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        p_req7516.actArea = p_req7515.actArea;
        Date date = new Date();
        p_req7516.dateFrom = Format.Date8Format.format(date);
        p_req7516.dateTo = Format.Date8Format.format(date);
        return d_7516_HisTrans(p_req7516);
    }
}
